/**
 * @author JINMO
 * @since 2022/06/28 19:42
 */

package com.cskaoyan.service.admin.impl;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.bo.MarketCartCheckedBo;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.bean.vo.cart.MarketCartCheckOutVo;
import com.cskaoyan.bean.vo.cart.MarketCartDeleteVo;
import com.cskaoyan.bean.vo.cart.MarketCartTotalVo;
import com.cskaoyan.bean.vo.cart.MarketCartVo;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.admin.MarketCartService;
import com.cskaoyan.util.CheckUserLoginUtils;
import com.cskaoyan.util.CurrentUserUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class MarketCartServiceImpl implements MarketCartService {


    @Autowired
    MarketCartMapper marketCartMapper;

    @Autowired
    MarketGoodsMapper marketGoodsMapper;

    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;

    @Autowired
    MarketAddressMapper marketAddressMapper;

    @Autowired
    MarketSystemMapper marketSystemMapper;

    @Autowired
    MarketCouponMapper marketCouponMapper;

    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    /**
     * 获取购物车的数据
     *
     * @return {@link MarketCartVo }
     * @author: jinmo
     * @date: 2022/06/28 19:42:49
     */
    @Override
    public MarketCartDeleteVo index() {
        //获得用户id
        // liuChun  使用工具类
        MarketUser user = CurrentUserUtils.getUser();
        //初始化参数准备赋值
        int goodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal(0);
        int checkGoodsCount = 0;
        BigDecimal checkGoodsAmount = new BigDecimal(0);
        //获取购物车中当前用户未删除的数据
        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andDeletedEqualTo(false).andUserIdEqualTo(user.getId());
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        //遍历，为参数赋值
        for (MarketCart marketCart : marketCarts) {
            goodsCount += marketCart.getNumber();
            goodsAmount = goodsAmount.add(marketCart.getPrice().multiply(new BigDecimal(marketCart.getNumber())));
            if (marketCart.getChecked()) {
                checkGoodsCount += marketCart.getNumber();
                checkGoodsAmount = checkGoodsAmount.add(marketCart.getPrice().multiply(new BigDecimal(marketCart.getNumber())));
            }
        }
        //为对象赋值
        MarketCartTotalVo marketCartVo = new MarketCartTotalVo();
        marketCartVo.setGoodsCount(goodsCount);
        marketCartVo.setCheckedGoodsCount(checkGoodsCount);
        marketCartVo.setGoodsAmount(goodsAmount);
        marketCartVo.setCheckedGoodsAmount(checkGoodsAmount);
        // marketCartVo.setCartList(marketCarts);

        MarketCartDeleteVo marketCartDeleteVo = new MarketCartDeleteVo();
        marketCartDeleteVo.setCartTotal(marketCartVo);
        marketCartDeleteVo.setCartList(marketCarts);

        return marketCartDeleteVo;
    }

    /**
     * 获得购物车指定id集合的数据，删除对应的购物车信息
     *
     * @param productIds 产品id
     * @return {@link MarketCartDeleteVo }
     * @author: jinmo
     * @date: 2022/06/29 16:34:10
     */
    @Transactional
    @Override
    public MarketCartDeleteVo delete(List<Integer> productIds) {
        //获得用户id
        MarketUser currentUser = CheckUserLoginUtils.checkUserLogin();
        //初始化参数准备赋值
        int goodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal(0);
        int checkGoodsCount = 0;
        BigDecimal checkGoodsAmount = new BigDecimal(0);
        //获取购物车中当前用户未删除对应规格的数据
        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andDeletedEqualTo(false).andUserIdEqualTo(currentUser.getId()).andProductIdNotIn(productIds);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        //遍历，为参数赋值
        for (MarketCart marketCart : marketCarts) {
            goodsCount += marketCart.getNumber();
            goodsAmount = goodsAmount.add(marketCart.getPrice().multiply(new BigDecimal(marketCart.getNumber())));
            if (marketCart.getChecked()) {
                checkGoodsCount += marketCart.getNumber();
                checkGoodsAmount = checkGoodsAmount.add(marketCart.getPrice().multiply(new BigDecimal(marketCart.getNumber())));
            }
        }
        //为对象赋值

        MarketCartDeleteVo data = new MarketCartDeleteVo();
        MarketCartTotalVo cartTotal = new MarketCartTotalVo();
        cartTotal.setGoodsCount(goodsCount);
        cartTotal.setCheckedGoodsCount(checkGoodsCount);
        cartTotal.setGoodsAmount(goodsAmount);
        cartTotal.setCheckedGoodsAmount(checkGoodsAmount);
        data.setCartTotal(cartTotal);
        data.setCartList(marketCarts);

        //删除操作
        MarketCartExample cartExample = new MarketCartExample();
        MarketCart cart = new MarketCart();
        cart.setDeleted(true);
        MarketCategoryExample categoryExample = new MarketCategoryExample();
        cartExample.createCriteria().andUserIdEqualTo(currentUser.getId()).andProductIdIn(productIds);
        marketCartMapper.updateByExampleSelective(cart, cartExample);

        return data;
    }

    /**
     * 添加商品到购物车,返回购物车的商品个数
     * 如果同一用户存在相同规格的商品，直接更新数量
     *
     * @param marketCart 市场车
     * @author: jinmo
     * @date: 2022/06/28 20:31:39
     */
    @Override
    public void add(MarketCart marketCart) {
        //获得用户id
        MarketUser currentUser = CheckUserLoginUtils.checkUserLogin();
        //对对象赋userId
        marketCart.setUserId(currentUser.getId());
        //判断购物车是否存在对应规格、对应用户的商品
        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andProductIdEqualTo(marketCart.getProductId()).andUserIdEqualTo(marketCart.getUserId()).andDeletedEqualTo(false);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        //如果存在，更新数量
        if (marketCarts.size() > 0) {
            MarketCart marketCartUnique = marketCarts.get(0);
            marketCartUnique.setChecked(true);
            marketCartUnique.setNumber((short) (marketCartUnique.getNumber() + marketCart.getNumber()));
            marketCartMapper.updateByPrimaryKey(marketCartUnique);
            return;
        }
        //不存在，添加
        //根据goodsId获得goods对象
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(marketCart.getGoodsId());
        //根据productId获得product对象
        MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(marketCart.getProductId());
        //为对象赋值
        marketCart.setGoodsSn(marketGoods.getGoodsSn());
        marketCart.setGoodsName(marketGoods.getName());
        marketCart.setPrice(marketGoodsProduct.getPrice());
        marketCart.setSpecifications(Arrays.toString(marketGoodsProduct.getSpecifications()));
        marketCart.setChecked(true);
        marketCart.setPicUrl(marketGoodsProduct.getUrl());
        Date date = new Date();
        marketCart.setAddTime(date);
        marketCart.setUpdateTime(date);
        marketCart.setDeleted(false);
        //插入数据库
        marketCartMapper.insertSelective(marketCart);

    }

    /**
     * 获取购物车商品件数
     *
     * @return {@link Integer }
     * @author: jinmo
     * @date: 2022/06/28 21:40:59
     */
    @Override
    public Integer goodsCount() {
        //获得用户id
        // lc 判空 未登录时默认userid为0
        Integer userId = 0;
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();
        if (!ObjectUtils.isEmpty(principals)) {
            MarketUser currentUser = (MarketUser) principals.getPrimaryPrincipal();
            userId = currentUser.getId();
        }
        //获得当前用户购物车中的数量
        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andDeletedEqualTo(false).andUserIdEqualTo(userId);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        int count = 0;
        for (MarketCart cart : marketCarts) {
            count += cart.getNumber();
        }
        return count;
    }

    /**
     * 选择或取消选择商品
     *
     * @param marketCartCheckedBo
     * @author: jinmo
     * @date: 2022/06/28 22:06:21
     */
    @Override
    public void checked(MarketCartCheckedBo marketCartCheckedBo) {
        // 获得用户id
        Subject subject = SecurityUtils.getSubject();
        MarketUser currentUser = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();

        marketCartMapper.updateCheckedByProductIds(marketCartCheckedBo.getIsChecked(), marketCartCheckedBo.getProductIds(), currentUser.getId());
    }


    /**
     * 下单前信息确认
     * 确认商品总金额、优惠券、运费、团购折扣、地址信息、商品信息
     *
     * @param marketCartCheckOutVo
     * @return {@link MarketCartCheckOutVo }
     * @author: jinmo
     * @date: 2022/06/29 14:05:51
     */
    @Override
    @Transactional
    public MarketCartCheckOutVo checkout(MarketCartCheckOutVo marketCartCheckOutVo) {
        //获得用户信息
        // Subject subject = SecurityUtils.getSubject();
        // MarketUser currentUser = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        MarketUser currentUser = CheckUserLoginUtils.checkUserLogin();
        Integer userId = currentUser.getId();
        //获得用户未删除的所有地址
        // MarketAddressExample marketAddressExample = new MarketAddressExample();
        // marketAddressExample.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        // List<MarketAddress> marketAddresses = marketAddressMapper.selectByExample(marketAddressExample);
        //获得用户地址
        MarketAddress checkedAddress = marketAddressMapper.selectByPrimaryKey(marketCartCheckOutVo.getAddressId());
        //如果cartId为0获得购物车中所有未被删除并选中的商品集合，不然获得对应购物车信息
        List<MarketCart> marketCarts = null;
        MarketCartExample marketCartExample = new MarketCartExample();
        if (marketCartCheckOutVo.getCartId() == 0) {
            marketCartExample.createCriteria().andUserIdEqualTo(userId).andCheckedEqualTo(true).andDeletedEqualTo(false);
            marketCarts = marketCartMapper.selectByExample(marketCartExample);
        } else {
            marketCartExample.createCriteria().andIdEqualTo(marketCartCheckOutVo.getCartId());
            marketCarts = marketCartMapper.selectByExample(marketCartExample);
        }
        BigDecimal goodsTotalPrice = new BigDecimal(0);
        Set<Integer> goodsIds = new HashSet<>();
        Set<Integer> categoryIds = new HashSet<>();
        for (MarketCart marketCart : marketCarts) {
            //根据集合求得商品总价格
            goodsTotalPrice = goodsTotalPrice.add(marketCart.getPrice().multiply(new BigDecimal(marketCart.getNumber())));
            //获得商品的所有不重复的商品id
            goodsIds.add(marketCart.getGoodsId());
            //获得商品的所有不重复的类目id
            categoryIds.add(marketGoodsMapper.selectByPrimaryKey(marketCart.getGoodsId()).getCategoryId());
        }
        //从数据库中获得系统常量，进一步得到，免除运费的金额以及一般运费价格
        List<MarketSystem> marketSystems = marketSystemMapper.selectByExample(null);
        //最小包邮价格
        BigDecimal marketExpressFreightMin = null;
        //运费
        BigDecimal marketExpressFreightValue = null;
        for (MarketSystem marketSystem : marketSystems) {
            if (marketSystem.getKeyName().equals("market_express_freight_min")) {
                marketExpressFreightMin = new BigDecimal(Integer.parseInt(marketSystem.getKeyValue()));
            }
            if (marketSystem.getKeyName().equals("market_express_freight_value")) {
                marketExpressFreightValue = new BigDecimal(Integer.parseInt(marketSystem.getKeyValue()));
            }
        }
        BigDecimal freightPrice = null;
        //是否需要支付运费
        if (goodsTotalPrice.compareTo(marketExpressFreightMin) > -1) {
            //如果大于最小包邮价格
            freightPrice = new BigDecimal(0);
        } else {
            //小于需要付运费
            freightPrice = marketExpressFreightValue;
        }
        //获得可用优惠券的数量
        MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
        //获得本用户下未删除状态码为0的优惠券
        marketCouponUserExample.createCriteria().andUserIdEqualTo(userId).andStatusEqualTo((short) 0).andDeletedEqualTo(false);
        List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
        //过滤不在有效区间类的优惠券
        Date date = new Date();
        List<MarketCouponUser> collect = marketCouponUsers.stream().
                filter(marketCouponUser -> marketCouponUser.getAddTime() == null || marketCouponUser.getAddTime().compareTo(date) < 1).
                filter(marketCouponUser -> marketCouponUser.getEndTime() == null || marketCouponUser.getEndTime().compareTo(date) > -1)
                .collect(Collectors.toList());
        //根据上面的信息获得对应的优惠券对象
        List<MarketCoupon> marketCoupons = new ArrayList<>();
        for (MarketCouponUser marketCouponUser : collect) {
            marketCoupons.add(marketCouponMapper.selectByPrimaryKey(marketCouponUser.getCouponId()));
        }
        //过滤掉不到对应价位和不是相关类目或商品的优惠券
        BigDecimal finalGoodsTotalPrice = goodsTotalPrice;
        List<MarketCoupon> coupons = marketCoupons.stream()
                //过滤不到对应价位
                .filter(marketCoupon -> marketCoupon.getMin().compareTo(finalGoodsTotalPrice) < 1)
                //过滤不是相关类目或商品
                .filter(marketCoupon -> {
                    if (marketCoupon.getGoodsType() == 0) {
                        return true;
                    } else if (marketCoupon.getGoodsType() == 1) {
                        //商品中有属于优惠券类目的就能通过
                        List<Integer> goodsValues = Arrays.asList(marketCoupon.getGoodsValue());
                        for (Integer categoryId : categoryIds) {
                            if (goodsValues.contains(categoryId)) {
                                return true;
                            }
                        }
                    } else if (marketCoupon.getGoodsType() == 2) {
                        //商品中有属于优惠券类目的就能通过
                        List<Integer> goodsValues = Arrays.asList(marketCoupon.getGoodsValue());
                        for (Integer goodsId : goodsIds) {
                            if (goodsValues.contains(goodsId)) {
                                return true;
                            }
                        }
                    }
                    return false;
                }).collect(Collectors.toList());
        Integer availableCouponLength = coupons.size();
        BigDecimal couponPrice = null;
            //如果CouponId>0则进一步判断，不然为0
            if (marketCartCheckOutVo.getCouponId() > 0) {
                //获得对应的优惠券
                MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(marketCartCheckOutVo.getCouponId());
                //如果优惠最小优惠价格大于总价格，优惠券不可用
                if (marketCoupon.getMin().compareTo(goodsTotalPrice) > 0) {
                    marketCartCheckOutVo.setUserCouponId(-1);
                    marketCartCheckOutVo.setCouponId(-1);
                    marketCartCheckOutVo.setCouponPrice(new BigDecimal(0));
                    couponPrice = new BigDecimal(0);
                } else {
                    //获得优惠价格
                    couponPrice = marketCoupon.getDiscount();
                }
            } else {
                couponPrice = new BigDecimal(0);
            }
        //求得实际价格和目标价格
        BigDecimal orderTotalPrice = goodsTotalPrice.subtract(couponPrice).add(freightPrice);
        //校验是否小于0
        if (orderTotalPrice.compareTo(new BigDecimal(0)) < 0) {
            orderTotalPrice = new BigDecimal(0);
        }
        BigDecimal actualPrice = orderTotalPrice;
        //团购未写

        //赋值
        marketCartCheckOutVo.setActualPrice(actualPrice);
        marketCartCheckOutVo.setAvailableCouponLength(availableCouponLength);
        marketCartCheckOutVo.setCheckedAddress(checkedAddress);
        marketCartCheckOutVo.setCheckedGoodsList(marketCarts);
        marketCartCheckOutVo.setCouponPrice(couponPrice);
        marketCartCheckOutVo.setFreightPrice(freightPrice);
        marketCartCheckOutVo.setGoodsTotalPrice(goodsTotalPrice);
        //团购价格默认为0
        marketCartCheckOutVo.setGrouponPrice(new BigDecimal(0));
        marketCartCheckOutVo.setOrderTotalPrice(orderTotalPrice);
        return marketCartCheckOutVo;


    }

    /**
     * 立即购买商品
     *
     * @param marketCart 市场车
     * @return
     * @author: jinmo
     * @date: 2022/06/29 15:29:49
     */
    @Transactional
    @Override
    public Integer fastadd(MarketCart marketCart) {
        //获得用户id
        // Subject subject = SecurityUtils.getSubject();
        // MarketUser currentUser = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        MarketUser currentUser = CheckUserLoginUtils.checkUserLogin();
        //对对象赋userId
        marketCart.setUserId(currentUser.getId());
        //判断购物车是否存在对应规格、对应用户的商品
        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andProductIdEqualTo(marketCart.getProductId()).andUserIdEqualTo(marketCart.getUserId()).andDeletedEqualTo(false);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        //如果存在，更新数量
        if (marketCarts.size() > 0) {
            MarketCart marketCartUnique = marketCarts.get(0);
            marketCartUnique.setChecked(true);
            //与添加购物车中不同
            marketCartUnique.setNumber((marketCart.getNumber()));
            marketCartMapper.updateByPrimaryKey(marketCartUnique);
            return marketCartUnique.getId();
        }
        //不存在，添加
        //根据goodsId获得goods对象
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(marketCart.getGoodsId());
        //根据productId获得product对象
        MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(marketCart.getProductId());
        //为对象赋值
        marketCart.setGoodsSn(marketGoods.getGoodsSn());
        marketCart.setGoodsName(marketGoods.getName());
        marketCart.setPrice(marketGoodsProduct.getPrice());
        marketCart.setSpecifications(Arrays.toString(marketGoodsProduct.getSpecifications()));
        marketCart.setChecked(true);
        marketCart.setPicUrl(marketGoodsProduct.getUrl());
        Date date = new Date();
        marketCart.setAddTime(date);
        marketCart.setUpdateTime(date);
        marketCart.setDeleted(false);
        //插入数据库
        marketCartMapper.insertSelective(marketCart);
        return marketCart.getId();
    }

    /**
     * 更新购物车 商品数量
     *
     * @param map
     * @return com.cskaoyan.bean.vo.BaseRespVo
     * @author Can
     * @since 2022/06/29 16:10
     */
    @Override
    public BaseRespVo update(Map map) {
        int goodsId = (Integer) map.get("goodsId");
        int id = (Integer) map.get("id");
        int number = (Integer) map.get("number");
        int productId = (Integer) map.get("productId");

        MarketGoodsProduct goodsProduct = marketGoodsProductMapper.selectByPrimaryKey(productId);
        if (goodsProduct.getNumber() < number) {
            return BaseRespVo.error(710, "库存不足");
        }
        MarketCart marketCart = new MarketCart();
        marketCart.setId(id);
        marketCart.setNumber((short) number);
        marketCartMapper.updateByPrimaryKeySelective(marketCart);
        return BaseRespVo.ok();
    }
}
